package com.lingz.manager.modules.camera.serviceimpl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lingz.manager.common.utils.RequestAuthorizationServiceUtil;
import com.lingz.manager.common.vo.SearchVo;
import com.lingz.manager.modules.camera.dao.CameraDao;
import com.lingz.manager.modules.camera.dao.mapper.CameraMapper;
import com.lingz.manager.modules.camera.entity.Camera;
import com.lingz.manager.modules.camera.service.CameraService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 摄像头接口实现
 * @author wx
 */
@Slf4j
@Service
@Transactional
public class CameraServiceImpl implements CameraService {

    @Autowired
    private CameraDao cameraDao;

    @Autowired
    private CameraMapper cameraMapper;

    @Override
    public CameraDao getRepository() {
        return cameraDao;
    }

    @Override
    public Page<Camera> findByCondition(Camera camera, SearchVo searchVo, Pageable pageable) {
        return cameraDao.findAll(new Specification<Camera>() {
            @Override
            public Predicate toPredicate(Root<Camera> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                Path<String> cameraName = root.get("cameraName");
                Path<Integer> cameraType = root.get("cameraType");
                Path<String> positionStatus = root.get("positionStatus");
                List<Predicate> list = new ArrayList<Predicate>();

                //快速索引
                if(StrUtil.isNotBlank(searchVo.getFasttips())){
                    list.add(cb.like(cameraName,'%'+searchVo.getFasttips()+'%'));
                    list.add(cb.equal(cameraType,searchVo.getFasttips()));
                    list.add(cb.equal(positionStatus,searchVo.getFasttips()));
                }

                //摄像头名称模糊搜素
                if(StrUtil.isNotBlank(camera.getCameraName())){
                    list.add(cb.like(cameraName,'%'+camera.getCameraName()+'%'));
                }

                //摄像头类型查询
                if(null != camera.getCameraType()){
                    list.add(cb.equal(cameraType,camera.getCameraType()));
                }

                //摄像头坐标状态
                if(StrUtil.isNotBlank(camera.getPositionStatus())){
                    list.add(cb.equal(positionStatus,camera.getPositionStatus()));
                }

                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr)).orderBy(cb.desc(positionStatus),cb.asc(cameraName));
                return null;
            }
        },pageable);
    }
    /**
     * 请求摄像头服务地址将数据同步到本地数据库
     * @param serviceUrl
     */
    @Override
    public void requestCameraListToDB(String serviceUrl) {
        //摄像头服务
        String cameraService = "/api/resource/v1/camera/advance/cameraList";
        //String cameraService = "/api/irds/v2/deviceResource/resources";
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("pageNo", 1);
        jsonBody.put("pageSize", 500);
        jsonBody.put("resourceType", "camera");
        String body = jsonBody.toJSONString();
        JSONObject jsonObject = RequestAuthorizationServiceUtil.requestService(cameraService, body);
        if (null != jsonObject && !jsonObject.isEmpty()) {
            JSONObject data = jsonObject.getJSONObject("data");
            System.out.println(data);
            //regionIndexCode -> a973f901-e473-452e-a0b4-554fb559b58b
            List<Camera> cameras = JSONArray.parseArray(data.getString("list"), Camera.class);
            List<Camera> list = new ArrayList<>();
            if (null != cameras && cameras.size() > 0) {
                cameras.stream().forEach(p -> {
                    //Camera camera = cameraDao.findByCameraIndexCode(p.getCameraIndexCode());
                    Camera camera = cameraMapper.findByCameraIndexCode(p.getCameraIndexCode());
                    p.setId(UUID.randomUUID().toString());
                    p.setLatitude(camera == null ? null : camera.getLatitude());
                    p.setLongitude(camera == null ? null : camera.getLongitude());
                    p.setAltitude(camera == null ? null : camera.getAltitude());
                    p.setType(camera == null ? null : camera.getType());
                    p.setPositionStatus(camera == null ? "0" : camera.getPositionStatus());
                    list.add(p);
                });
            }

            cameraMapper.deleteAll();
            cameraMapper.insertBatch(list);
        }
    }

}